package com.catering.until;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class CommonUtils {
	/**
     * 获取request
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }
	
	//检查是否为不加入的查询条件
	private static String[] UNCHECK_LIST = new String[]{"page","size","limit","index","selectType","orderByType","orderByAscType","groupByType","betweenByType","ltEqByType","gtEqByType","ltByType","gtByType"};
	
    public static QueryWrapper getKeySet(Map<String, String> map,String flag) {
    	QueryWrapper wrapper = new QueryWrapper();
    	try {
    		if (map != null) {
    			Set<String> keySet = map.keySet();
    			for (String key : keySet) {
    				String val = String.valueOf(map.get(key));
    				if (!Arrays.asList(UNCHECK_LIST).contains(key)) {
    					if(checkNoNull(flag)){
    						if(humpToLine(key).contains("id")) {
    							if(key.contains(".")) wrapper.eq(checkNoNull(val),humpToLine(key), val);
    							else wrapper.eq(checkNoNull(val), flag + "." + humpToLine(key), val);
    						} else {
    							if(val.contains("至")) wrapper.between(flag + "." + humpToLine(key), val.split("至")[0].trim(),val.split("至")[1].trim());
    							else if(val.contains(",")) wrapper.between(flag + "." + humpToLine(key), val.split(",")[0].trim(),val.split(",")[1].trim());
    							else if(val.contains("<->")) wrapper.in(flag + "." + humpToLine(key), val.split("<->"));
    							else if(key.contains(".")) wrapper.like(checkNoNull(val),humpToLine(key), val);
    							else wrapper.like(checkNoNull(val), flag + "." + humpToLine(key), val);
    						}
    					}else{
    						if(humpToLine(key).contains("id")) wrapper.eq(checkNoNull(val), humpToLine(key), val);
    						else {
    							if(val.contains("至")) wrapper.between(humpToLine(key), val.split("至")[0].trim(),val.split("至")[1].trim());
    							else if(val.contains(",")) wrapper.between(humpToLine(key), val.split(",")[0].trim(),val.split(",")[1].trim());
    							else if(val.contains("<->")) {
    								wrapper.in(humpToLine(key), Arrays.asList(val.split("<->")));
    							}
    							else wrapper.like(checkNoNull(val), humpToLine(key), val);
    						}
    					}
    				}else {
						if(key.contains("orderByType")) {
							String[] byType = val.split(",");
							for(String str : byType) {
								if(str.contains(".")) wrapper.orderByDesc(humpToLine(str));
								else wrapper.orderByDesc(checkNoNull(flag) ? flag + "." + humpToLine(str) : humpToLine(str));
							}
						}else if(key.contains("orderByAscType")){
							String[] byType = val.split(",");
							for(String str : byType) {
								if(str.contains(".")) wrapper.orderByAsc(humpToLine(str));
								else wrapper.orderByAsc(checkNoNull(flag) ? flag + "." + humpToLine(str) : humpToLine(str));
							}
						}else if(key.contains("groupByType")){
							String[] byType = val.split(",");
							for(String str : byType) {
								if(str.contains(".")) wrapper.groupBy(humpToLine(str));
								else wrapper.groupBy(checkNoNull(flag) ? flag + "." + humpToLine(str) : humpToLine(str));
							}
						}else if(key.contains("betweenByType")){
							//例如:betweenByType:"t1.column,val1,val2"
							String[] byType = val.split(",");
							if(val.contains(".")) wrapper.between(humpToLine(byType[0]),byType[1],byType[2]);
							else wrapper.between(checkNoNull(flag) ? flag + "." + humpToLine(byType[0]) : humpToLine(byType[0]),byType[1],byType[2]);
						}else if(key.contains("ltEqByType")){
							String[] ltType = val.split(",");
							if(val.contains(".")) wrapper.le(humpToLine(key),val);
							else wrapper.le(checkNoNull(flag) ? flag + "." + humpToLine(ltType[0]) : humpToLine(ltType[0]),ltType[1]);
						}else if(key.contains("gtEqByType")){
							String[] gtType = val.split(",");
							if(val.contains(".")) wrapper.ge(humpToLine(gtType[0]),gtType[1]);
							else wrapper.ge(checkNoNull(flag) ? flag + "." + humpToLine(gtType[0]) : humpToLine(gtType[0]),gtType[1]);
						}else if(key.contains("ltByType")){
							String[] ltType = val.split(",");
							if(val.contains(".")) wrapper.le(humpToLine(key),val);
							else wrapper.lt(checkNoNull(flag) ? flag + "." + humpToLine(ltType[0]) : humpToLine(ltType[0]),ltType[1]);
						}else if(key.contains("gtByType")){
							String[] gtType = val.split(",");
							if(val.contains(".")) wrapper.ge(humpToLine(gtType[0]),gtType[1]);
							else wrapper.gt(checkNoNull(flag) ? flag + "." + humpToLine(gtType[0]) : humpToLine(gtType[0]),gtType[1]);
						}
    				}
    			}
    		} 
    	}catch (Exception e) {
    		e.printStackTrace();
		}
    	return wrapper;
    }
    
    public static QueryWrapper getKeySet(Map<String,Object> map) {
		QueryWrapper wrapper =new QueryWrapper<>();
		if(map != null) {
			Set<String> keySet = map.keySet();
			for (String key : keySet) {
				if(!key.equals("page") && !key.equals("size") && !key.equals("limit") && !key.equals("platformIds")) {
					wrapper.like(map.get(key) != null && map.get(key) != "" && !map.get(key).equals(""),humpToLine(key),map.get(key));
				}
			}
		}
		return wrapper;
	}
    
    public static boolean checkNoNull(Object param) {
    	if(param != null && !"".equals(param) && param != "" && param != "null") {
    		return true;
    	}
    	return false;
    }
    
    public static boolean checkNull(Object param) {
    	if(!checkNoNull(param)) {
    		return true;
    	}
    	return false;
    }
    
    //非驼峰转换
    public static QueryWrapper getNoKeySet(Map<String, String> map) {
    	QueryWrapper wrapper = new QueryWrapper();
    	if (map != null) {
    		Set<String> keySet = map.keySet();
    		for (String key : keySet) {
    			if (!key.equals("page") && !key.equals("size") && !key.equals("limit") && !key.equals("index") && !key.equals("selectType") && !key.contains("orderByType")) {
    				if(key.contains("id") || key.contains("Id")) {
    					wrapper.eq((map.get(key) != null && map.get(key) != "" && !map.get(key).equals("")), key, map.get(key)); 
    				}else {
    					wrapper.like((map.get(key) != null && map.get(key) != "" && !map.get(key).equals("")), key, map.get(key)); 
    				}
    			}
    		} 
    	} 
    	return wrapper;
    }

	public static String getUuid(){
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	/**获取时间*/
	public static String getTime(int i) {
		if(i == 23) {
			SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
			return sbf.format(new Date());
		}else if(i == 19) {
			SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sbf.format(new Date());
		}else if(i == 17) {
				SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				return sbf.format(new Date());
		}else if(i == 10) {
			SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd");
			return sbf.format(new Date());
		}else if(i == 7) {
			SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM");
			return sbf.format(new Date());
		}else {
			return String.valueOf(System.currentTimeMillis());
		}
	}
	
	/** 驼峰转下划线(简单写法) */
	public static String humpToLine(String str) {
		return str.replaceAll("[A-Z]", "_$0").toLowerCase();
	}
	
    //向上取整
    public static int mathCeil(int dividend,int divisor) {
    	if ((dividend % divisor) == 0) {
			return (int)dividend / (int)divisor;               // 将操作数转化为int型数据
		} else {
			return  ((int)dividend / (int)divisor) + 1;         // 将操作数转化为int型数据
		}
    }
    
    /**
     * 占比计算保留小数的位数方法
     * 转成百分数
     * 当前数除以总数
     *
     * @param num1 ,num2  num1/num2
     * @return rate  保留2位小数的
     */
    public static String division(int num1, int num2) {
        String rate = "0.00%";
        //定义格式化起始位数
        String format = "0.00";
        if (num2 != 0 && num1 != 0) {
            DecimalFormat dec = new DecimalFormat(format);
            rate = dec.format((double) num1 / num2 * 100) + "%";
            while (true) {
                if (rate.equals(format + "%")) {
                    format = format + "0";
                    DecimalFormat dec1 = new DecimalFormat(format);
                    rate = dec1.format((double) num1 / num2 * 100) + "%";
                } else {
                    break;
                }
            }
        } else if (num1 != 0 && num2 == 0) {
            rate = "100%";
        }
        return rate;
    }
    
    /**
     * 把上面得到的百分比转为字符串类型的小数  保留两位小数
     *
     * @author shw
     */
    public static BigDecimal perToDecimal(String percent) {
        String decimal = percent.substring(0, percent.indexOf("%"));
        BigDecimal bigDecimal = new BigDecimal(decimal);
        bigDecimal.divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_UP);
        return bigDecimal;
    }
    /**
     * 保留两位小数
     *
     * @author shw
     */
    public static Double perToDecimal(Double f) {
    	//尾数为0去掉
    	return Double.valueOf(String.format("%.2f", f).replaceAll("0+?$", "").replaceAll("[.]$", ""));
    }
    
    /**
  	 * 将string时间格式字符串转换成date类型
  	 * @param str
  	 * @return
  	 * @throws ParseException
  	 */
  	public static Date stringToDate(String str,String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			return sdf.parse(str);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}
  	/**
  	 * 将date时间格式字符串转换成string类型
  	 * @param str
  	 * @return
  	 * @throws ParseException
  	 */
  	public static String dateToString(Date str,String format) throws ParseException {
  		SimpleDateFormat sdf = new SimpleDateFormat(format);
  		return sdf.format(str);
  	}
    
    /**
     * 在给定的日期加上或减去指定 天数或月份 后的日期
     *
     * @param str 原始时间
     * @param type 年月日
     * @param num      要调整的月份/天数，向前为负数，向后为正数
     * @param format    格式  "yyyy-MM-dd HH:mm:ss"
     * @return
     */
    public static String stepTime(String str, int num,String type,String format){
    	Calendar c = Calendar.getInstance();
    	Date sourceDate = null;
		if(checkNoNull(str)) sourceDate = stringToDate(str,format);
		else sourceDate = new Date();
    	DateFormat dateFormat = new SimpleDateFormat(format);
    	c.setTime(sourceDate);
    	if("month".equals(type)) c.add(Calendar.MONTH, num);
    	else c.add(Calendar.DATE, num);
        return dateFormat.format(c.getTime());
    }
    
  	/**
  	 * Excel数字时间转成时间格式
  	 * @param strDate
  	 * @return
  	 */
  	public static String excelDoubleToDate(String strDate) {
        if(strDate.length() == 5){
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date tDate = doubleToDate(Double.parseDouble(strDate));
                return sdf.format(tDate);
            }catch (Exception e){
                e.printStackTrace();
                return strDate;
            }
        }
        return strDate;
    }
  	public static Date doubleToDate(Double dVal) {
        Date tDate = new Date();
        long localOffset = tDate.getTimezoneOffset() * 60000; //系统时区偏移 1900/1/1 到 1970/1/1 的 25569 天
        tDate.setTime((long) ((dVal - 25569) * 24 * 3600 * 1000 + localOffset));

        return tDate;
    }
  	
  	/**
  	 * 删除文件(服务器路径下的文件)
  	 * @param map 文件名称和类型
  	 * @return
  	 */
  	public static boolean delFile(Map<String,String> map) {
  		boolean flag = false;
		String fileName = map.get("fileName");
		String filePath = map.get("filePath");
  		log.info("进入deFile方法,删除的文件名称 fileName =: "+fileName);
  		try{
			String truePath = filePath + "/" + fileName;
	  	    File file = new File(truePath);
	  	    log.info("操作服务器文件列表如下:"+file);
	  	    if (!file.exists()) {
	  	        return flag;
	  	    }
  	        flag = file.delete();
  	        log.info("删除结果:"+flag);
  	    }catch (Exception e){
  	        e.printStackTrace();
  	    }
  		return flag;
  	}
  	
  	/**
  	 * 计算两个时间相差的时/分/秒
  	 * @param startTime
  	 * @param endTime
  	 * @param str
  	 * @return
  	 */
  	public static Long dateDiff(String startTime,String endTime,String str) {
		String[] starts = startTime.split(" ");
		String[] ends = endTime.split(" ");
		if(starts.length == 1) startTime = startTime + " 00:00:00";
		if(ends.length == 1) endTime = endTime + " 00:00:00";
        // 按照传入的格式生成一个simpledateformate对象  
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        // 获得两个时间的毫秒时间差异  
        try {  
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();  
            day = diff / nd;// 计算差多少天  
            hour = diff % nd / nh + day * 24;// 计算差多少小时  
            min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟  
            sec = diff % nd % nh % nm / ns;// 计算差多少秒  
            // 输出结果  
//            System.out.println("时间相差：" + day + "天" + (hour - day * 24) + "小时" 
//                    + (min - day * 24 * 60) + "分钟" + sec + "秒。");  
//            System.out.println("hour=" + hour + ",min=" + min);  
            if(str.equals("h")) {  
                return hour;  
            }else if(str.equals("m")){  
                return min;  
            }else if(str.equals("d")){  
            	return day;  
            }else {
            	//return sec;
            	return diff/1000;
            }
        } catch (ParseException e) {  
            e.printStackTrace();  
        }
		return sec;  
  	}

	/**
	 * 返回java.util.Date
	 *
	 * 给原本的时间originDate加上自定义的时间
	 * @param originDate 原本的时间
	 * @param day 要加的天数
	 * @param hour 要加的小时数
	 * @param minute 要加的分钟数
	 * @param second 要加的秒数
	 * @return 返回加完时间后的时间goalDate
	 */
	public static Date addDateTimeToDate(Date originDate, int day, int hour, int minute,int second) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(originDate);
		cal.add(Calendar.DATE, day);// 24小时制,加天
		cal.add(Calendar.HOUR, hour);// 24小时制 ,加小时
		cal.add(Calendar.MINUTE, minute);// 24小时制,加分钟
		cal.add(Calendar.SECOND, second);// 24小时制,加秒

		Date goalDate = cal.getTime();
		return goalDate;
	}

	/**
	 * 返回字符串
	 *
	 * 给原本的时间originDate加上自定义的时间
	 * @param originDate 原本的时间
	 * @param day 要加的天数
	 * @param hour 要加的小时数
	 * @param minute 要加的分钟数
	 * @param second 要加的秒数
	 * @return 返回加完时间后的时间str_goalDate
	 */
	public static String addDateTimeToStr(Date originDate, int day, int hour, int minute,int second,String format) {
		SimpleDateFormat dateFormate = new SimpleDateFormat(format);
		Calendar cal = Calendar.getInstance();
		cal.setTime(originDate);
		cal.add(Calendar.DATE, day);// 24小时制,加天
		cal.add(Calendar.HOUR, hour);// 24小时制 ,加小时
		cal.add(Calendar.MINUTE, minute);// 24小时制,加分钟
		cal.add(Calendar.SECOND, second);// 24小时制,加秒

		String str_goalDate = dateFormate.format(cal.getTime());
		return str_goalDate;
	}

  	/**
  	 * 将秒转化成时间
  	 * @param second
  	 * @return
  	 */
  	public static String changeTimeFormat(String second) {
		Integer seconds = Integer.valueOf(second);
		if (seconds > 0 && seconds < 60) {//小于1分钟
			return seconds + "秒";
		} else if (seconds >= 60 && seconds < 3600) {//大于等于1分钟小于1小时
			int changeM = (int) Math.floor(seconds / 60);//整分钟数
			int surplusM = (int) Math.floor(seconds % 60);//余下的秒数
			if (surplusM > 0) {//余数不为0秒
				return changeM + "分" + surplusM + "秒";
			} else {//整分钟，没有余数
				return changeM + "分";
			}
		} else if (seconds >= 3600) {//大于1小时
			int changeH = (int) Math.floor(seconds / 3600);//整小时数
			int surplusH = (int) Math.floor(seconds % 3600);//剩下的秒数
			if (surplusH >= 60) {//余数大于大于1分钟
				int changeM = (int) Math.floor(surplusH / 60);
				int surplusM = (int) Math.floor(surplusH % 60);
				if (surplusM > 0) {//余数大于0
					return changeH + "小时" + changeM + "分" + surplusM + "秒";
				} else {//整分钟，没有余数
					return changeH + "小时" + changeM + "分";
				}
			} else if (surplusH < 60 && surplusH > 0) {//余数小于1分钟，大于0秒
				int surplusM = (int) Math.floor(surplusH % 1024);
				return changeH + "小时" + surplusM + "秒";
			} else {
				return changeH + "小时";
			}
			//Double hour = new BigDecimal((float) seconds / (60 * 60)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			//return hour + "小时";
		}
		return "0秒";
	}
  	
  	/**
  	 * 将两个日期的时间段按照一定天数进行周期切割
  	 * @param cycleNum
  	 * @param startTime
  	 * @param endTime
  	 * @return
  	 * @throws ParseException
  	 */
    public  static List<Map> getCycleList(int cycleNum,String startTime,String endTime) throws ParseException {
      //  System.out.println("统计的时间段为：从"+startTime+"到"+endTime);
        Date endParse = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
        Long endLong = endParse.getTime();
 
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//这个是你要转成后的时间的格式
        endTime = sdf.format(new Date(endLong));
 
        int daysBetweenNum = daysBetween(startTime, endTime);
        int cycleForNum = daysBetweenNum % cycleNum == 0 ? (daysBetweenNum / cycleNum) : (daysBetweenNum / cycleNum) + 1;
        Date startParse = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
        Long startLong = startParse.getTime();
        Long calculationLong = startLong;
        List<Map> list=new ArrayList();
        for (int i = 1; i <= cycleForNum; i++) {
            String startStr = sdf.format(new Date(calculationLong));
            Date startStrParse = new SimpleDateFormat("yyyy-MM-dd").parse(startStr);
            Long startStrLong = startStrParse.getTime();
            Long cycleLong = cycleNum*86400000l;
            calculationLong = startStrLong + cycleLong;
            String endStr = endTime;
            if (calculationLong <= endLong) {
                endStr = sdf.format(new Date(calculationLong));
            }
            Map map=new HashMap();
            map.put("time",startStr+"~"+endStr);
            list.add(map);
        }
      //  System.out.println("周期list："+list.toString());
        return list;
    }
    
    public static int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
 
    }
    
    /**
     * 判断一个时间是否在两个时间内
     * @param d1 开始时间
     * @param d2 结束时间
     * @param innerTime 判断时间
     * @return
     */
    public static boolean isInnerTime(String d1,String d2,String innerTime) {
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    	try {
	    	Date dt1 = formatter.parse(d1);
	    	Date dt2 = formatter.parse(d2);
	    	Date stime = dt1.before(dt2) ? dt1 : dt2;
	    	Date etime = dt1.after(dt2) ? dt1 : dt2;
	    	Date inner = formatter.parse(innerTime);
	    	boolean flag = inner.after(stime) && inner.before(etime);
	    //	System.out.println("是否在2个时间之间:" + flag);
	    	return flag;
    	} catch (Exception e) {
    		e.printStackTrace();
    		return false;
    	}
	}
    
    /**
     * 判断是否为纯数字
     * @param cs
     * @return
     */
    public static boolean checkStrIsNum(final CharSequence cs) {
        // 判断是否为空，如果为空则返回false
        if (cs == null) {
            return false;
        }
        // 通过 length() 方法计算cs传入进来的字符串的长度，并将字符串长度存放到sz中
        final int sz = cs.length();
        // 通过字符串长度循环
        for (int i = 0; i < sz; i++) {
            // 判断每一个字符是否为数字，如果其中有一个字符不满足，则返回false
            if (!Character.isDigit(cs.charAt(i))) {
                return false;
            }
        }
        // 验证全部通过则返回true
        return true;
    }
    
    /**
     * 计算两个时间之间的月份集合
     * @param y1 开始时间
     * @param y2 结束时间
     * @return
     */
    public static List<String> getMonthList(String y1,String y2){
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM").parse(y1);
            Date endDate = new SimpleDateFormat("yyyy-MM").parse(y2);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            // 获取开始年份和开始月份
            int startYear = calendar.get(Calendar.YEAR);
            int startMonth = calendar.get(Calendar.MONTH);
            // 获取结束年份和结束月份
            calendar.setTime(endDate);
            int endYear = calendar.get(Calendar.YEAR);
            int endMonth = calendar.get(Calendar.MONTH);
            List<String> list = new ArrayList<String>();
            for (int i = startYear; i <= endYear; i++) {
                String date = "";
                if (startYear == endYear) {
                    for (int j = startMonth; j <= endMonth; j++) {
                        if (j < 9) {
                            date = i + "-0" + (j + 1);
                        } else {
                            date = i + "-" + (j + 1);
                        }
                        list.add(date);
                    }
                } else {
                    if (i == startYear) {
                        for (int j = startMonth; j < 12; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    } else if (i == endYear) {
                        for (int j = 0; j <= endMonth; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    } else {
                        for (int j = 0; j < 12; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    }
                }
            }
            // 所有的月份已经准备好
            //System.out.println(list);
            for(int i = 0;i < list.size();i++){
                list.get(i);
            }
            return list;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取两个日期之间的所有日期集合（yyyy-MM-dd）
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }
    
    /**
     * 获取当前时间之前的指定时间（小时）
     * @param num
     * @return
     */
    public static String beforeHourDate(int num) {
    	Calendar calendar = Calendar.getInstance();
    	/* HOUR_OF_DAY 指示一天中的小时 */
    	calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - num);
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
    	return df.format(calendar.getTime());

	}
    
    /**
     * 获取指定日期月的每一天日期
     * @param date
     * @return
     */
    public static List<String> getAllDateOfMonth(String date) {
    	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    	Date dd = null;
		try {
			dd = dateFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		List<String> list = new ArrayList<String>();
		Calendar cal = Calendar.getInstance();
		cal.setTime(dd);
		cal.set(Calendar.DATE, 1);
		int month = cal.get(Calendar.MONTH);
		while(cal.get(Calendar.MONTH) == month){
			list.add(dateFormat.format(cal.getTime()));
			cal.add(Calendar.DATE, 1);
		}
		return list;
	}
    
    /**
     * 将数字转换为小时
     * @param time
     * @return
     */
    public static String getTimeAdd(String time) {
    	if(time == null) return null;
    	if(checkStrIsNum(time)) {
    		Integer s = Integer.valueOf(time);
    		if(s > -1 && s < 9) {
    			return "0"+s+":00"+"~"+"0"+(s+1)+":00";
    		}else if(s == 9) {
    			return "0"+s+":00"+"~"+(s+1)+":00";
    		}else {
    			return s+":00"+"~"+(s+1)+":00";
    		}
    	}
    	return null;
    }
    
    /**
     * 四舍五入
     * @param f
     * @return
     */
    public static String rounding(Double f) {
        BigDecimal bg = new BigDecimal(f);
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(f1);
    }

    /**
     * 开始分页
     * @param list
     * @param pageNum 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static List startPage(List list, Integer pageNum, Integer pageSize) {
        if (list == null || list.size() == 0) {  return null; }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List pageList = list.subList(fromIndex, toIndex);
        return pageList;
    }
    
    /**
     * 获取本周的第一天
     * @return String
     * **/
    public static String getWeekStart(){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, 0);
        cal.set(Calendar.DAY_OF_WEEK, 2);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }
    
    /**
     * 获取本周的最后一天
     * @return String
     * **/
    public static String getWeekEnd(){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
        cal.add(Calendar.DAY_OF_WEEK, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }
    
    /** 
     * 获得指定日期 上 n 周第一天 周一:yyyy-MM-dd
     */
    public static String getWeekStartDay(int n,String day) {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = null;
        try {
            time = sdf.parse(day);
        } catch(ParseException e) {
            e.printStackTrace();
        }
        c.setTime(time);
        c.set(Calendar.DAY_OF_WEEK,2);
        c.add(Calendar.DATE, -7*n);
        SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-dd  00:00:00");
        return startSdf.format(c.getTime());
    }
    
    /** 
     * 获得指定日期 上 n 周最后一天 周日:yyyy-MM-dd
     */
    public static String getWeekEndDay(int n,String day) {
    	Calendar c = Calendar.getInstance();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Date time = null;
    	try {
    		time = sdf.parse(day);
    	} catch(ParseException e) {
    		e.printStackTrace();
    	}
    	c.setTime(time);
    	c.set(Calendar.DAY_OF_WEEK,c.getActualMaximum(Calendar.DAY_OF_WEEK));
    	c.add(Calendar.DATE, -7*n+1);
    	SimpleDateFormat startSdf = new SimpleDateFormat("yyyy-MM-dd  00:00:00");
    	return startSdf.format(c.getTime());
    }
    
    /**
     * 获取当前周几
     * @param dt
     * @return
     */
    public static String getWeekOfDate() {
     // String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
    	String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(new Date());
    	int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
    	if (w < 0) w = 0;
    	return weekDays[w];
    }
    
    /**
     * 自定义生成单号
     * @param title
     * @return
     */
    public static String getRandomByTime(String title) {
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
    	String newDate=sdf.format(new Date());
    	String result="";
    	Random random=new Random();
    	for(int i=0;i<3;i++){
    		result+=random.nextInt(10);
    	}
    	return title+newDate+result;
    }
    
    /**
    * 取两个文本之间的文本值
    * @param text 源文本 比如：欲取全文本为 12345
    * @param left 文本前面
    * @param right 后面文本
    * @return 返回 String
    */
    public static String getSubString(String text, String left, String right) {
	    String result = "";
	    int zLen;
	    if (left == null || left.isEmpty()) {
	    	zLen = 0;
	    } else {
	    	zLen = text.indexOf(left);
	    	if (zLen > -1) {
	    		zLen += left.length();
	    	} else {
	    		zLen = 0;
	    	}
	    }
	    int yLen = text.indexOf(right, zLen);
	    if (yLen < 0 || right == null || right.isEmpty()) {
	    	yLen = text.length();
	    }
	    result = text.substring(zLen, yLen);
	    return result;
    }
    /**
     * 将数据库int对应的string类型的字段为空转换为0
     * @param str
     * @return
     */
    public static String charToInt(Object str) {
    	if(!checkNoNull(str)) return "0";
    	else return String.valueOf(str);
    }
	
    /**
     * 将对象装换为map
     *
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }
	/**
	 * @param srcPath     原图片地址
	 * @param desPath     目标图片地址
	 * @param desFileSize 指定图片大小，单位kb
	 * @param accuracy    精度，递归压缩的比率，建议小于0.9
	 * @return            图片压缩成功或者失败
	 */
	public static boolean compressPicForScale(String srcPath, String desPath, long desFileSize, double accuracy) {
		try {
			File srcFile = new File(srcPath);
			long srcFilesize = srcFile.length();
			log.info("原文件:" + srcPath + ",大小:" + srcFilesize / 1024 + "kb");
			//递归压缩，直到目标文件大小小于desFileSize
			compressPicCycle(desPath, desFileSize, accuracy);

			File desFile = new File(desPath);
			log.info("目标文件:" + desPath + ",大小" + desFile.length() / 1024 + "kb");
			log.info("文件压缩完成!");
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	//递归压缩，直到目标文件大小小于desFileSize
	public static void compressPicCycle(String desPath, long desFileSize,double accuracy) throws IOException {
		File imgFile = new File(desPath);
		long fileSize = imgFile.length();
		//判断大小，如果小于指定大小，不压缩；如果大于等于指定大小，压缩
		if (fileSize <= desFileSize * 1024) {
			return;
		}
		//计算宽高
		BufferedImage bim = ImageIO.read(imgFile);
		int imgWidth = bim.getWidth();
		int imgHeight = bim.getHeight();
		int desWidth = new BigDecimal(imgWidth).multiply(
				new BigDecimal(accuracy)).intValue();
		int desHeight = new BigDecimal(imgHeight).multiply(
				new BigDecimal(accuracy)).intValue();
		Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
		//如果不满足要求，递归直至满足指定大小的要求
		compressPicCycle(desPath, desFileSize, accuracy);
	}
}
